package org.example.c2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 通过synchroinzed解决不能停止的worker问题
 * <p>
 * synchonized能保证原子性和可见性，这里通过可见性使得可以获取到最新值
 */
@Slf4j
public class Demo16 {
    public static void main(String[] args) throws InterruptedException {
        Worker w = new Worker();

        w.start();
        TimeUnit.SECONDS.sleep(5);
        log.info("send stop command");
        w.stop();
    }

    static class Worker {
        private boolean running = false;

        public void start() {
            running = true;
            new Thread(() -> {
                log.info("begin..");
                while (true) {
                    synchronized (this) { //通过可见性，获取到内存中的新值
                        if (!running) {
                            break;
                        }
                    }
                }
                log.info("stopped");
            }, "t1").start();
        }

        public synchronized void stop() {
            running = false;
        }
    }
}
